#include <QThread>
#include <QDebug>
#include <cstdlib>
#include <unistd.h>

#include "ReaderWriter.h"

size_t Worker::N = 0;

Reader::Reader(Library& alibrary) : library(alibrary) {}

void Reader::action() {
    size_t maxBookIndex =
            library.getLibSize();

    if (maxBookIndex == 0) {
        usleep(library.getReaderInterval() * 1000);
        return;
    }

    size_t bookn = random() % maxBookIndex;
    qDebug() << id << "Starting reading the Book: " << bookn;
    QSharedPointer<QMutex> book = library.getBook(bookn);
    usleep(library.getReaderInterval() * 1000);
    qDebug() << id << "Finished reading the Book: " << bookn;
    library.returnBook(book);
}

Writer::Writer(Library &alibrary) : library(alibrary) {}

void Writer::action() {
    size_t maxBookIndex = library.getLibSize();

    // New book writing
    if (maxBookIndex == 0 || (!(random() % 4) && !library.isFull())) {
        qDebug() << id << " Has started writing the new book";
        usleep(library.getReaderInterval() * 1000);
        int bookn = library.add();
        qDebug() << id << " wrote a book:" << bookn;
    } else { // Editing the existing book
        int book_n = random() % maxBookIndex;
        qDebug() << id << " starting editing the book";
        QSharedPointer<QMutex> book = library.getBook(book_n);
        usleep(library.getWriterInterval() * 1000);
        qDebug() << id << " finished with editing: " << book_n;
        library.returnBook(book);
    }
}
